package main

import (
	"fmt"
	"net"
	"sort"
	"sync"
	"time"
)
var wg sync.WaitGroup
var lock sync.Mutex
func worker(ports, results chan int) {
		for p := range ports {
			
			defer wg.Done()
			address := fmt.Sprintf("sunnysport.hzpt.edu.cn:%d", p)
			conn, err := net.DialTimeout("tcp", address,3*time.Second)
			if err != nil {
				results <- 0
				fmt.Println(err)
				continue
			}
			conn.Close()
			results <- p
		}
}

func main() {
	ports := make(chan int,2)
	results := make(chan int)
	var openports []int
	for i := 0; i < cap(ports); i++ {
		go worker(ports, results)
	}

	go func() {
		for i := 3300;i < 3320;i++ {
			wg.Add(1)
			ports <- i
		}
	}()



	for i := 3300; i < 3320; i++ {
		port := <-results
		if port != 0 {
			lock.Lock()
			openports = append(openports, port)
			lock.Unlock()
		}
	}

	close(ports)
	close(results)
	wg.Wait()
	//将开放的端口排序输出
	sort.Ints(openports)
	for _, port := range openports {
		fmt.Printf("%d open\n", port)
	}
}
